/**
 * 
 */
package com.bjtct.plugin.autogen.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * mysql实例，
 * 
 * @author syf
 *
 */
@SuppressWarnings("serial")
public class MySql implements IDataBase {
 
 
	private static MySql instance = null;

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		}

	}

	public static MySql instance() {
		if (instance == null) {
			instance = new MySql();
		}

		return instance;
	}

	private MySql() {
		super();
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.bjtct.plugin.autogen.db.IDataBase#getTables()
	 */
	@Override
	public List<DbTable> getTables(String url, String user, String pwd, String db) {
		String sql = "select table_name name,table_type type, table_comment mark from information_schema.tables where table_schema= ?";
		PreparedStatement st = null;
		Connection con = null;
		ResultSet rs = null;
		List<DbTable> tables = new ArrayList<DbTable>();
		try {
			con = DbUtils.getCon(user, pwd, url);
			st = con.prepareStatement(sql);
			st.setString(1, db);
			rs = st.executeQuery();
			while (rs.next()) {

				DbTable t = new DbTable(rs.getString("name"), rs.getString("type"), rs.getString("mark"));
				tables.add(t);
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DbUtils.colse(con, rs, st);
		}

		return tables;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.bjtct.plugin.autogen.db.IDataBase#getColumns()
	 */
	@Override
	public List<ColumnWrap> getColumns(String url, String user, String pwd, String target) {
		String sql = "select  column_name, data_type, column_type, is_nullable, column_key,column_comment,column_default ,extra from information_schema.columns where table_name=? ";
		PreparedStatement st = null;
		Connection con = null;
		ResultSet rs = null;
		List<ColumnWrap> columns = new ArrayList<ColumnWrap>();
		try {
			con = DbUtils.getCon(user, pwd, url);
			st = con.prepareStatement(sql);
			st.setString(1, target);
			rs = st.executeQuery();
			while (rs.next()) {

				DbColumn t = new DbColumn(rs.getString("column_name"), rs.getString("data_type"),
						rs.getString("column_type"), rs.getString("is_nullable"), rs.getString("column_key"),
						rs.getString("column_comment"), rs.getString("column_default"),rs.getString("extra"));

				columns.add(DbUtils.wrap(t));
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DbUtils.colse(con, rs, st);
		}
		return columns;
	}

	 

}
